#include "core.h"

#include <stdexcept>
#include <QMutexLocker>
#include <QApplication>
#include <QList>
#include <QDebug>
class Core::CorePrivate{
public:
	CorePrivate();
	~CorePrivate();

	SettingsSQL *m_pSettings;
	PluginsManager *m_pPluginsManager;
	QObject *m_pDatabase;

	QList<ISettings*> m_settingPages;
};

Core::CorePrivate::CorePrivate() :
	m_pSettings(NULL),
	m_pPluginsManager(NULL),
	m_pDatabase(NULL)
{
}

Core::CorePrivate::~CorePrivate(){
	//delete m_pDatabase; //pluginManager zwolni pamięć
	delete m_pPluginsManager;
	delete m_pSettings;

	m_pPluginsManager = NULL;
	m_pSettings = NULL;
	//m_pDatabase = NULL;
}

//end of d-class part
//------------------------------------------------------------------------------

Core::Core() :
	QObject(0),
	d(new CorePrivate())
{
	qDebug()<<"----->KONSTRUKTOR<-----";

	d->m_pSettings = new SettingsSQL( SettingsSQL::UserScope,
									  qApp->applicationName(),
									  QString(), "client_conf", this );
	d->m_pPluginsManager = new PluginsManager( this );

	QString dbFile = d->m_pSettings->value( Setting::databaseFileKey,
											QVariant() ).toString();

	if( !dbFile.isEmpty() ){
		d->m_pDatabase = d->m_pPluginsManager->loadPlugin( dbFile );
		if( !d->m_pDatabase )
			qWarning() << "Core => DB plugin file not loaded, check if exist";
	}

}


Core::~Core(){
	delete d;
	qDebug()<<"----->DESTRUKTOR<-----";
}


Core* Core::m_pInstance = NULL;


Core* Core::instance(){
	static QMutex mutex;
	if( !m_pInstance ){
		mutex.lock();
		if( !m_pInstance ){

			try{
				m_pInstance = new Core();
			}catch(std::bad_alloc){
				m_pInstance = NULL;
				mutex.unlock();
				return NULL;
			}

		}
		mutex.unlock();
	}

	return m_pInstance;
}

void Core::setInstance(Core *singleton){
	m_pInstance = singleton;
}

void Core::drop(){
	static QMutex mutex;
	mutex.lock();

	delete m_pInstance;

	m_pInstance = NULL;
	mutex.unlock();
}

//end of singleton part

void Core::registerSettingPage(ISettings *page){
	d->m_settingPages.push_back( page );
}

bool Core::unregisterSettingPage(ISettings *page){
	return d->m_settingPages.removeOne( page );
}

const QList<ISettings*>& Core::getSettingsPages() const {
	return d->m_settingPages;
}

SettingsSQL* Core::settings(){
	return d->m_pSettings;
}

PluginsManager* Core::pluginsManager(){
	return d->m_pPluginsManager;
}

QObject* Core::database(QString fileName){
	if( d->m_pDatabase )
		return d->m_pDatabase;

	if( fileName.isEmpty() ){
		qWarning() << "Core::database => empty fileName, unable to load plugin";
		return NULL;
	}



	d->m_pDatabase = d->m_pPluginsManager->loadPlugin( fileName );
	if( !d->m_pDatabase ){
		qWarning() << "Core::database => DB plugin file not loaded, "
				"check if exist";
	}else{
		return d->m_pDatabase;
	}

	return NULL;
}
